﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
using GPSMap.Core.Misc.DAL;
using HTMapLib;
using MapControl;
using MapControl.Misc;
using MapControl.Misc.DAL;
using MapControl.Misc.GPSPoint;
using MapXLib;
using Point = System.Drawing.Point;

namespace GPSMap
{
    public partial class ucReviewGPSData : UserControl
    {
        public ucVectShapeMap _objMapControl;
        public DataTable _dtRoute;
        public int _routeIndex;
        private Dictionary<string, string> _fileList = new Dictionary<string, string>();
        private string _backupDatapath = "";
        public ucReviewGPSData(frmGPSTracking objFrmGPSTracking, ComPort comPort)
        {
            InitializeComponent();
            _objMapControl = objFrmGPSTracking.mapControl;
            GeneralClass.IsViewLatestGPSPoint = false;
        }

        private void ucGPSData_Load(object sender, EventArgs e)
        {
            InitGPSGridViewControl();

            InitTrackBar();
            //tabControlFunction.Size = new Size(503, 200);
            splitContainer2.SplitterDistance = splitContainer2.Height - 140;
            _backupDatapath = Path.GetDirectoryName(Application.ExecutablePath) + "\\BackupData";
            string[] files = Directory.GetFiles(_backupDatapath);
            //Nếu thư mục có nhiều hơn 1 file thì upload
            if (files.Length >= 1)
            {
                string name = "";
                foreach (string file in files)
                {
                    name = Path.GetFileName(file);
                    _fileList.Add(name, file);
                    listBoxDataList.Items.Add(name);
                }
            }
            btnPause.Visible = false;
        }


        #region "GPSGridView Controls"

        public void LoadAirport()
        {
            _objUcGPSGridView.LoadAirport();
        }

        /// <summary>
        /// 2014-11-06
        /// </summary>
        public void LoadCombobox_Planes()
        {
            _objUcGPSGridView.LoadCombobox_Planes();
        }

        private void InitGPSGridViewControl()
        {
            //_objUcGPSGridView = new ucGPSDataGridView(_objMapControl);
            _objUcGPSGridView.InitControl(_objMapControl, true);
            //_objUcGPSGridView.DataGridViewGPSData_MouseDoubleClickEvent += new System.Windows.Forms.MouseEventHandler(this.dataGridViewGPSData_MouseDoubleClick);
            //_objUcGPSGridView.DataGridViewGPSData_CurrentCellChangedEvent += new EventHandler(this.dataGridViewGPSData_CurrentCellChanged);
            _objUcGPSGridView.Dock = DockStyle.Fill;
            splitContainer2.Panel1.Controls.Add(_objUcGPSGridView);
        }

        //private void dataGridViewGPSData_MouseDoubleClick(object sender, MouseEventArgs e)
        //{
        //    if (_objUcGPSGridView.DataGridViewGPS.CurrentRow != null)
        //    {
        //        BaseGPSPoint objPoint = new GPSNormalPoint(GeneralClass.dbTestGPS.Rows[_objUcGPSGridView.DataGridViewGPS.CurrentCell.RowIndex]);
        //        _objMapControl.ucMap1.Map.ZoomTo(_objMapControl.ucMap1.Map.Zoom, objPoint.objGPSData.LonGPS, objPoint.objGPSData.LatGPS);
        //        _objMapControl.Refresh();

        //        Graphics g = _objMapControl.ucMap1.Map.CreateGraphics();
        //        objPoint.Draw(g, Color.Red);
        //    }
        //}

        //private void dataGridViewGPSData_CurrentCellChanged(object sender, EventArgs e)
        //{
        //    if (_objUcGPSGridView.DataGridViewGPS.CurrentRow != null)
        //    {
        //        int airport_id = int.Parse(GeneralClass.dbTestGPS.Rows[_objUcGPSGridView.DataGridViewGPS.CurrentCell.RowIndex]["airport_id"].ToString());
        //        Airport objAirport = _airPortRespository.GetAirportById(airport_id);

        //        BaseGPSPoint objPoint = new GPSNormalPoint(GeneralClass.dbTestGPS.Rows[_objUcGPSGridView.DataGridViewGPS.CurrentCell.RowIndex]);
        //        toolStripStatusLabel1.Text = string.Format("Cách sân bay \"{0}\" khoảng {1} km", objAirport.Airport_Name, objPoint.objGPSData.Distance.ToString("#,##0"));
        //    }
        //}
        #endregion

        private void ucGPSData_Resize(object sender, EventArgs e)
        {
            trackBarLeft.Size = new Size(panelTrackBarLeft.Size.Width/2, trackBarLeft.Size.Height);
        }

        private void InitTrackBar()
        {
            trackBarLeft.Minimum = 0;
            trackBarRight.Minimum = 1;
            trackBarLeft.Maximum = _objUcGPSGridView.DataGridViewGPS.Rows.Count;
            trackBarRight.Maximum = _objUcGPSGridView.DataGridViewGPS.Rows.Count;
            trackBarLeft.Value = 0;
            trackBarRight.Value = trackBarRight.Maximum;
            //lblValueLeft.Text = trackBarLeft.Value.ToString("#,##0");
            numericUpDownLeft.Value = trackBarLeft.Value;
            //lblValueRight.Text = trackBarRight.Value.ToString("#,##0");
            numericUpDownRight.Value = trackBarRight.Value;
            

        }
        /// <summary>
        /// Thay đổi giá trị min max của trackbar
        /// </summary>
        private void TrackBarValueChanged()
        {
            GeneralClass.min = trackBarLeft.Value;
            GeneralClass.max = trackBarRight.Value;
            _objUcGPSGridView.LoadDataGridView(trackBarLeft.Value, trackBarRight.Value);
            //Lấy tọa độ mới nhất của các đường bay
            GeneralClass.GetCurrGPSDataArr();
            //GeneralClass.currGPSData = new GPSCurrentPoint(GeneralClass.dbTestGPS.Rows[GeneralClass.dbTestGPS.Rows.Count - 1]);
                
            _objMapControl.Refresh();
        }

        private void trackBarRight_ValueChanged(object sender, EventArgs e)
        {
            if (trackBarRight.Value < trackBarLeft.Value)
            {
                trackBarRight.Value = trackBarLeft.Value;
            }
            //numericUpDownRight.Text = trackBarRight.Value.ToString();
            numericUpDownRight.Value = trackBarRight.Value;
            TrackBarValueChanged();    
            
        }

        private void trackBarLeft_ValueChanged(object sender, EventArgs e)
        {
            if (trackBarLeft.Value > trackBarRight.Value)
            {
                trackBarLeft.Value = trackBarRight.Value;
            }
            numericUpDownLeft.Value = trackBarLeft.Value;
            TrackBarValueChanged();
        }

        private void LoadDataFile(string fileName)
        {
            try
            {
                GeneralClass.gpsDBFile = fileName;
                txtFilePath.Text = fileName;
                GPSDataRepository.ConnectionString = string.Format("DataSource={0}; Password=''", fileName);
                GeneralClass.UpgradeGPSData();
                GeneralClass.min = GeneralClass.max = 0;
                GeneralClass.LoadPlaneList();
                _objUcGPSGridView.LoadDataGridView(0, 0);
                _objUcGPSGridView.LoadCombobox_Planes();
                InitTrackBar();
                _objMapControl.Refresh();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }
        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (GeneralClass.objPort.IsOpen())
                {
                    MessageBox.Show("Cổng COM đang mở. Chỉ chọn xem lại file CSDL khác khi đã đóng cổng COM.");
                    return;
                }

                OpenFileDialog obj = new OpenFileDialog();
                obj.Multiselect = false;
                obj.ShowDialog();
                if (obj.FileName != "")
                {
                   LoadDataFile(obj.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

       
        private int indexReplay = 0;
        private DataTable dbReplay;
        public void btnReplay_Click(object sender, EventArgs e)
        {
            try
            {
                if (GeneralClass.IsReplay == 0) //Nếu đang dừng thì Start replay
                {
                    //Ẩn các control
                    numericUpDownLeft.Enabled = false;
                    numericUpDownRight.Enabled = false;
                    trackBarLeft.Enabled = false;
                    trackBarRight.Enabled = false;
                    labelSpeed.Visible = false;
                    numericUpDownSpeed.Visible = false;
                    //btnPause.Location = new Point(labelSpeed.Location.X, btnPause.Location.Y);
                    btnPause.Visible = true;

                    GeneralClass.IsReplay = 1;
                    btnReplay.Text = "Kết thúc chạy";
                    btnPause.Text = "Tạm dừng";
                    GeneralClass.dbTestGPS.Clear();
                    if (GeneralClass.objCurrPlane != null)
                        dbReplay = GPSDataRepository.LoadDatabase(GeneralClass.objCurrPlane.Code, trackBarLeft.Value, trackBarRight.Value);
                    else
                        dbReplay = GPSDataRepository.LoadDatabase(trackBarLeft.Value, trackBarRight.Value);
                    foreach (DataRow r in dbReplay.Rows)
                    {
                        r["showname"] = GeneralClass.planeDict[r["name"].ToString().Trim()];
                    }
                    _objUcGPSGridView.UpdateStatus(false);
                    HistoryRouteTimer.Interval = (int)((float)numericUpDownSpeed.Value * 1000);
                    HistoryRouteTimer.Start();
                }
                else //Nếu không phải đang chạy thì Stop replay
                {
                    //Ẩn các control
                    numericUpDownLeft.Enabled = true;
                    numericUpDownRight.Enabled = true;
                    trackBarLeft.Enabled = true;
                    trackBarRight.Enabled = true;
                    labelSpeed.Visible = true;
                    numericUpDownSpeed.Visible = true;
                    btnPause.Visible = false;

                    GeneralClass.IsReplay = 0;
                    btnReplay.Text = "Xem lại quá trình bay";
                    btnPause.Text = "Tạm dừng";
                    indexReplay = 0;
                    HistoryRouteTimer.Stop();
                    _objUcGPSGridView.LoadDataGridView(trackBarLeft.Value, trackBarRight.Value);
                    _objUcGPSGridView.UpdateStatus(true);
                    //Lấy tọa độ mới nhất của các đường bay
                    GeneralClass.GetCurrGPSDataArr();
                    //GeneralClass.currGPSData = new GPSCurrentPoint(GeneralClass.dbTestGPS.Rows[GeneralClass.dbTestGPS.Rows.Count - 1]);
                        
                    _objMapControl.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void numericUpDownLeft_ValueChanged(object sender, EventArgs e)
        {
            if (numericUpDownLeft.Value > numericUpDownRight.Value)
            {
                numericUpDownLeft.Value = numericUpDownRight.Value;
                trackBarLeft.Value = (int)numericUpDownLeft.Value;
            }
            else
            {
                trackBarLeft.Value = (int)numericUpDownLeft.Value;
            }
        }

        private void numericUpDownRight_ValueChanged(object sender, EventArgs e)
        {
            if (numericUpDownRight.Value < numericUpDownLeft.Value)
            {
                numericUpDownRight.Value = numericUpDownLeft.Value;
                trackBarRight.Value = (int)numericUpDownRight.Value;
            }
            else
            {
                trackBarRight.Value = (int)numericUpDownRight.Value;
            }
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            if (GeneralClass.IsReplay == 1) //Nếu đang chạy thì nhấn tạm dừng
            {
                GeneralClass.IsReplay = 2;
                btnPause.Text = "Chạy tiếp";
                HistoryRouteTimer.Stop();
            }
            else if (GeneralClass.IsReplay == 2) //Nếu đang tạm dừng thì nhấn chạy tiếp
            {
                GeneralClass.IsReplay = 1;
                btnPause.Text = "Tạm dừng";
                HistoryRouteTimer.Start();
            }
        }

        private void HistoryRouteTimer_Tick(object sender, EventArgs e)
        {
            if (indexReplay < dbReplay.Rows.Count)
            {
                
                //Copy datarow
                GeneralClass.dbTestGPS.ImportRow(dbReplay.Rows[indexReplay++]);
                _objUcGPSGridView.DataGridViewGPS.Rows[_objUcGPSGridView.DataGridViewGPS.Rows.Count - 1].Selected = true;
                _objUcGPSGridView.DataGridViewGPS.FirstDisplayedScrollingRowIndex = GeneralClass.dbTestGPS.Rows.Count - 1;
                _objUcGPSGridView.DataGridViewGPS.PerformLayout();
                
                //Cập nhật lại tọa độ mới nhất của các đường bay
                GPSCurrentPoint currGPSData = new GPSCurrentPoint(GeneralClass.dbTestGPS.Rows[GeneralClass.dbTestGPS.Rows.Count - 1]);
                GeneralClass.currGPSDataArr[currGPSData.objGPSData.Name] = currGPSData;

                _objMapControl.Refresh();
            }
            else //Nếu replay xong
            {
                btnReplay.PerformClick();
                //Nếu bật chức năng lặp lại
                if (checkBoxIsLoop.Checked)
                {
                    btnReplay.PerformClick();
                }
            }
        }

        private void listBoxDataList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (GeneralClass.objPort.IsOpen())
            {
                MessageBox.Show("Cổng COM đang mở. Chỉ chọn xem lại file CSDL khác khi đã đóng cổng COM.");
                return;
            }
            if (listBoxDataList.SelectedItem != null)
                LoadDataFile(_backupDatapath + "\\" + listBoxDataList.SelectedItem);
        }

        private void listBoxDataList_MouseDown(object sender, MouseEventArgs e)
        {
            listBoxDataList.SelectedIndex = listBoxDataList.IndexFromPoint(e.X, e.Y);
            if (e.Button == MouseButtons.Right)
            {
                listBoxDataList.ContextMenuStrip = contextMenuStrip1;
                contextMenuStrip1.Show(listBoxDataList, new Point(e.X, e.Y));
            }
            listBoxDataList.ContextMenuStrip = null;
        }

        private void xóaFileDữLiệuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn thật sự muốn xóa file này?", "Cảnh báo", MessageBoxButtons.YesNo) ==
                DialogResult.Yes)
            {
                string path = _backupDatapath + "\\" + listBoxDataList.SelectedItem;
                File.Delete(path);
                listBoxDataList.Items.RemoveAt(listBoxDataList.SelectedIndex);
                //Reset dữ liệu
                _objUcGPSGridView.Reset();
                GeneralClass.gpsDBFile = "";
                GeneralClass.dbTestGPS.Clear();
                GeneralClass.currGPSDataArr.Clear();
                _objMapControl.Refresh();
            }
        }

        
    }
}
